package com.check;

import com.check.config.AppConfig;
import com.check.config.PlaywrightConfigBean;
import com.check.config.YamlConfigLoader;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class Run {
    private static final AppConfig appConfig = YamlConfigLoader.load("config.yml", AppConfig.class);

    public static void main(String[] args) {
        // 系统环境变量
        System.out.println("==============ENVIRONMENTVARIABLE==============");
        for (Map.Entry<String, String> environmentVariableEntry : System.getenv().entrySet()) {
            String key = environmentVariableEntry.getKey();
            if (key.toLowerCase().contains("playwright")) {
                System.out.println("key:" + key + " value:" + environmentVariableEntry.getValue());
            }
        }
        // 系统属性
        System.out.println("==============SYSTEMPROPERTY==============");
        PlaywrightConfigBean playwrightConfigBean = appConfig.getPlaywrightConfigBean();
        String playwrightCliDir = playwrightConfigBean.getPlaywright_cli_dir();
        if (playwrightCliDir != null) {
            System.setProperty("playwright.cli.dir", playwrightCliDir);
        }
        System.out.println("playwright.cli.dir: " + playwrightCliDir);
        System.out.println("==============Options Env Map==============");
        HashMap<String, String> envMap = new HashMap<>();
        if (playwrightConfigBean.getPlaywrightSkipBrowserDownload() != null) {
            envMap.put("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", playwrightConfigBean.getPlaywrightSkipBrowserDownload());
        }
        if (playwrightConfigBean.getPlaywright_nodejs_path() != null) {
            envMap.put("PLAYWRIGHT_NODEJS_PATH", playwrightConfigBean.getPlaywright_nodejs_path());
        }
        for (Map.Entry<String, String> entry : envMap.entrySet()) {
            System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
        }
        String browserType = appConfig.getBrowserType();
        if (browserType == null) {
            System.out.println("browserType is null");
            return;
        }
        System.out.println("browserType: " + browserType);
        String wsEndpoint = appConfig.getWsEndpoint();
        if (browserType.equals("docker")) {
            if (wsEndpoint == null) {
                System.err.println("wsEndpoint is null");
                return;
            }
            System.out.println("wsEndpoint: " + wsEndpoint);
        } else if (browserType.equals("disk")) {
            String playwrightNodejsPath = appConfig.getPlaywrightConfigBean().getPlaywright_nodejs_path();
            if (appConfig.getPlaywrightConfigBean().getPlaywright_nodejs_path()==null) {
                if(playwrightCliDir!=null){
                    System.out.println("use cli playwright_nodejs, path:"+playwrightCliDir+"/node or node.exe");
                }else{
                    System.out.println("use program defaults to nodejs paths");
                }
            }else{
                System.out.println("use config nodejs, path:"+playwrightNodejsPath);
            }
        } else {
            System.out.println("Unknown browser type");
            return;
        }
        System.out.println("start create playwright");
        try (Playwright playwright = Playwright.create(
                new Playwright.CreateOptions().setEnv(envMap))) {
            System.out.println("create playwright successBrowser");
            BrowserType chromiumType = playwright.chromium();

            Browser browser;
            if (browserType.equals("docker")) {
                browser = chromiumType.connect(wsEndpoint);
            } else {
                browser = chromiumType.launch();
            }
            String internet = appConfig.getInternet();
            if ("T".equals(internet)) {
                screenshotUrl(browser, "https://example.com", "example.com.png");
            } else if ("F".equals(internet)) {
                screenshotHtml(browser,
                        "<html><title>Playwright Test</title><body><h1>Playwright Local Test</h1><p>No Internet Needed.</p></body></html>",
                        "Playwright_Test.png");
            } else if ("ALL".equals(internet)) {
                screenshotUrl(browser, "https://example.com", "example.com.png");
                screenshotHtml(browser,
                        "<html><title>Playwright Test</title><body><h1>Playwright Local Test</h1><p>No Internet Needed.</p></body></html>",
                        "Playwright_Test.png");
            } else {
                System.err.println("❌ internet Incorrect parameters:" + internet);
            }
        }
    }
    private static void screenshotUrl(Browser browser, String url, String fileName) {
        Page page = browser.newPage();
        page.navigate(url);
        page.screenshot(new Page.ScreenshotOptions()
                .setPath(Paths.get(fileName))
                .setFullPage(true));
        System.out.println("url screenshot success");
        page.close();
    }

    private static void screenshotHtml(Browser browser, String html, String fileName) {
        Page page = browser.newPage();
        page.setContent(html);
        page.screenshot(new Page.ScreenshotOptions()
                .setPath(Paths.get(fileName))
                .setFullPage(true));
        System.out.println("html screenshot success");
        page.close();
    }
}